package io.renren.modules.app.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.renren.common.utils.*;
import io.renren.modules.app.annotation.LoginUser;
import io.renren.modules.app.entity.*;
import io.renren.modules.app.service.*;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品api
 * @author zzh
 * @email 862583291@qq.com
 * @date 2019-6-15 12:27
 */
@Api("商品api")
@RestController
@RequestMapping("/app/v1/goods")
public class ApiGoodsController {

    @Autowired
    private ApiGoodsService apiGoodsService;

    @Autowired
    private ApiGoodsSpecificationService apiGoodsSpecificationService;

    @Autowired
    private ApiProductService apiProductService;

    @Autowired
    private ApiGoodsGalleryService apiGoodsGalleryService;

    @Autowired
    private ApiAttributeService apiAttributeService;

    @Autowired
    private ApiGoodsIssueService apiGoodsIssueService;

    @Autowired
    private ApiCommentService apiCommentService;

    @Autowired
    private ApiCommentPictureService apiCommentPictureService;

    @Autowired
    private ApiUserService apiUserService;

    @Autowired
    private ApiCollectService apiCollectService;

    @Autowired
    private ApiFootprintService apiFootprintService;


    /**
     *查询新增的商品
     */
    @GetMapping("/newGoods")
    public R newGoods(){
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("fields", "id, name, list_pic_url, retail_price, market_price");
        params.put("isNew", 1);
        params.put("isDelete", 0);
        params.put("isOnSale", 1);
        params.put("page", "1");
        params.put("limit", "6");
        Query query = new Query(params);
        List<GoodsVo> goodsList = apiGoodsService.queryList(query);
        int total = apiGoodsService.queryTotal(query);
        PageUtils pageUtil = new PageUtils(goodsList, total, query.getLimit(), query.getCurrPage());
        return R.ok().put("data", pageUtil);
    }

    /**
     *查询热销的商品
     */
    @GetMapping("/hotGoods")
    public R hotGoods(){
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("fields", "id, name, list_pic_url, retail_price, market_price");
        params.put("isHot", 1);
        params.put("isDelete", 0);
        params.put("isOnSale", 1);
        params.put("page", "1");
        params.put("limit", "6");
        Query query = new Query(params);
        List<GoodsVo> goodsList = apiGoodsService.queryList(query);
        int total = apiGoodsService.queryTotal(query);
        PageUtils pageUtil = new PageUtils(goodsList, total, query.getLimit(), query.getCurrPage());
        return R.ok().put("data", pageUtil);
    }

    /**
     *条件查询商品列表
     * categoryId
     * page
     * limit
     * sidx
     * order
     */
    @GetMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        if (StringUtil.isNullOrEmpty(params.get("categoryId"))) {
            return R.error("参数不能为空");
        }
        Page<GoodsVo> page = (Page<GoodsVo>) apiGoodsService.page(
            new Query<GoodsVo>(params).getPage(),
            new QueryWrapper<GoodsVo>()
                    .eq("is_delete","0")
                    .eq("is_on_sale","1")
                    .eq("category_id",params.get("categoryId"))
                    .orderBy(!StringUtil.isNullOrEmpty(params.get("sidx")),((String)params.get("order")).equalsIgnoreCase("asc"),(String)params.get("sidx"))
        );
        return R.ok().put("data",new PageUtils(page));
    }

    /**
     *商品详情页数据
     */
    @GetMapping("/detail")
    public R detail(Long userId, Integer id, Long referrer){
        GoodsVo goodsInfo = apiGoodsService.getById(id);
        Map param = new HashMap();
        param.put("goods_id", id);
        //获得商品规格信息
        Map specificationParam = new HashMap();
        specificationParam.put("fields", "gs.*, s.name");
        specificationParam.put("goods_id", id);
        specificationParam.put("specification", true);
        specificationParam.put("sidx", "s.sort_order");
        specificationParam.put("order", "asc");
        List<GoodsSpecificationVo> goodsSpecificationEntityList = apiGoodsSpecificationService.queryList(specificationParam);

        List<Map> specificationList = new ArrayList();
        //按规格名称分组
        for (int i = 0; i < goodsSpecificationEntityList.size(); i++) {
            GoodsSpecificationVo specItem = goodsSpecificationEntityList.get(i);
            List<GoodsSpecificationVo> tempList = null;
            for (int j = 0; j < specificationList.size(); j++) {
                if (specificationList.get(j).get("specificationId").equals(specItem.getSpecificationId())) {
                    tempList = (List<GoodsSpecificationVo>) specificationList.get(j).get("valueList");
                    break;
                }
            }
            if (null == tempList) {
                Map temp = new HashMap();
                temp.put("specificationId", specItem.getSpecificationId());
                temp.put("name", specItem.getName());
                tempList = new ArrayList();
                tempList.add(specItem);
                temp.put("valueList", tempList);
                specificationList.add(temp);
            } else {
                for (int j = 0; j < specificationList.size(); j++) {
                    if (specificationList.get(j).get("specificationId").equals(specItem.getSpecificationId())) {
                        tempList = (List<GoodsSpecificationVo>) specificationList.get(j).get("valueList");
                        tempList.add(specItem);
                        break;
                    }
                }
            }
        }
        //拿到产品信息
        List<ProductVo> productList = apiProductService.queryList(param);
        //拿到商品轮播图信息
        List<GoodsGalleryVo> gallery = apiGoodsGalleryService.list(
                new QueryWrapper<GoodsGalleryVo>().eq("goods_id",id).orderByDesc("sort_order")
        );
        //拿到商品属性信息
        Map ngaParam = new HashMap();
        ngaParam.put("fields", "nga.value, na.name");
        ngaParam.put("sidx", "nga.id");
        ngaParam.put("order", "asc");
        ngaParam.put("goods_id", id);
        List<AttributeVo> attribute = apiAttributeService.queryList(ngaParam);
        //得到问题清单
        List<GoodsIssueVo> issue = apiGoodsIssueService.list(
                new QueryWrapper<GoodsIssueVo>().eq("goods_id",id)
        );
        //得到商品评价信息
        Integer commentCount = apiCommentService.count(
                new QueryWrapper<CommentVo>().eq("value_id",id).eq("type_id",0).eq("status",1)
        );
        List<CommentVo> hotComment = apiCommentService.list(
                new QueryWrapper<CommentVo>().eq("value_id",id).eq("type_id",0).eq("status",1)
        );
        Map commentInfo = new HashMap();
        if (null != hotComment && hotComment.size() > 0) {
            UserVo commentUser = apiUserService.getById(hotComment.get(0).getUserId());
            commentInfo.put("content", Base64.decode(hotComment.get(0).getContent()));
            commentInfo.put("addTime", DateUtils.timeToStr(hotComment.get(0).getAddTime(), DateUtils.DATE_PATTERN));
            commentInfo.put("nickname", commentUser.getNickname());
            commentInfo.put("avatar", commentUser.getAvatar());
            List<CommentPictureVo> commentPictureEntities = apiCommentPictureService.list(
                    new QueryWrapper<CommentPictureVo>().eq("comment_id",hotComment.get(0).getId())
            );
            commentInfo.put("picList", commentPictureEntities);
        }
        Map comment = new HashMap();
        comment.put("count", commentCount);
        comment.put("data", commentInfo);
        //当前用户是否收藏
        Integer userHasCollect = 0;
        userHasCollect = apiCollectService.count(
                new QueryWrapper<CollectVo>().eq("value_id",id).eq("type_id",0).eq("user_id",userId)
        );
        if (userHasCollect > 0) {
            userHasCollect = 1;
        }
        //记录用户的足迹
        if(userId != null){
            FootprintVo footprintEntity = new FootprintVo();
            footprintEntity.setUserId(userId);
            footprintEntity.setGoodsId(goodsInfo.getId());
            footprintEntity.setAddTime(System.currentTimeMillis() / 1000);
            if (null != referrer) {
                footprintEntity.setReferrer(referrer);
            } else {
                footprintEntity.setReferrer(0L);
            }
            apiFootprintService.save(footprintEntity);
        }
        Integer visitorVolume = apiFootprintService.count(
                new QueryWrapper<FootprintVo>().eq("goods_id",id)
        );
        goodsInfo.setVisitorVolume(visitorVolume);

        // 记录推荐人是否可以领取红包，用户登录时校验



        return R.ok()
                .put("goodsInfo",goodsInfo)
                .put("specificationList",specificationList)
                .put("productList",productList)
                .put("gallery",gallery)
                .put("attribute",attribute)
                .put("issue",issue)
                .put("comment",comment)
                .put("userHasCollect",userHasCollect);
    }

}
